package pers.rcl.common.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;
import org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor;

import javax.servlet.http.HttpServletRequest;

/**
 * 指定注解格式的参数解析器/校验
 *
 * @Author LiuBao
 * @Version 2.0 2017年9月3日
 * @see RequestResponseBodyMethodProcessor
 */
@Slf4j
public class AuthParamArgumentResolver implements HandlerMethodArgumentResolver {
    private static final String JSON_REQUEST_BODY = "JSON_REQUEST_BODY";

    @Value("${param.invalid.interval:60}")
    private long invalidInterval;

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        //TODO 对自定义注解参数进行校验，带有自定义注解的参数进行参数解析；
        //return false 时不对参数自定义解析；return true时对参数进行自定义解析
        boolean result = false;
        boolean annotation = parameter.hasParameterAnnotation(AuthParam.class);
        if (annotation) {
            AuthParam authParam = parameter.getParameterAnnotation(AuthParam.class);
            if (authParam != null) {
                result = authParam.required();
            }
        }
        return result;
    }

    /**
     * 当支持后进行相应的转换/校验
     */
    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
                                  NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        AuthParam authParam = parameter.getParameterAnnotation(AuthParam.class);
        HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class);
        //TODO 获取请求体里面的内容，注：请求体为json格式
        //TODO 解析参数中出现异常直接抛出，通过统一异常类进行返回
        String jsonBody = request.getAttribute(JSON_REQUEST_BODY) == null ? "" : request.getAttribute(JSON_REQUEST_BODY).toString();

        //TODO 根据请求信息对其进行解析，解析后返回相对应的参数
        return "";
    }


}